<!--
 * @Author: likaijie 847094299@qq.com
 * @Date: 2025-04-07 10:09:46
 * @LastEditors: 深海有鱼 847094299@qq.com
 * @LastEditTime: 2025-09-05 16:47:08
 * @Description: 
-->
<template>
  <div class="provider-list-page">
    <div>
      <el-button type="primary" @click="openConfigDialog(false)">
        新增服务配置
      </el-button>
    </div>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="provider">
        <el-select
          v-model="form.provider"
          placeholder="请选择供应商"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in providerOptions"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="激活状态" prop="isActive">
        <el-select
          v-model="form.isActive"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option label="激活" :value="true" />
          <el-option label="未激活" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon('ep:refresh')"
          @click="resetForm(formRef)"
        >
          重置
        </el-button>
        <!-- <el-button type="success" @click="openSyncServices">
          同步第三方服务配置
        </el-button>
        <el-button type="success" @click="resetInitialSyncedApi">
          重置所有初始同步标志
        </el-button> -->
        <!-- <el-button
          type="success"
          :disabled="!selectionList.length"
          @click="openDialog(selectionList)"
        >
          批量更新服务提供商价格
        </el-button> -->
      </el-form-item>
    </el-form>
    <ServicePriceDialog ref="servicePriceDialogRef" @refresh="onSearch" />
    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="name" label="名称" min-width="120" sortable />
      <el-table-column
        prop="apiName"
        label="Api名称"
        min-width="100"
        sortable
      />
      <el-table-column prop="minLineCount" label="最小行数" width="100" />
      <el-table-column prop="maxLineCount" label="最大行数" width="100" />
      <el-table-column
        prop="standardCode"
        label="服务类型"
        width="180"
        sortable
      />
      <el-table-column prop="displayImage" label="图片" width="180">
        <template #default="{ row }">
          <div class="img-box">
            <el-image
              :src="row.image || taskConfigStore.getIcon(row.standardCode)"
              fit="contain"
              style="height: 40px; width: 120px"
            >
              <template #error>
                <div class="image-slot">暂无图片</div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="adapterType" label="适配器" width="120" sortable />
      <el-table-column
        prop="apiProvider"
        label="提供商名称"
        min-width="140"
        sortable
      />
      <el-table-column prop="costScore" label="价格" width="100" sortable />
      <el-table-column
        prop="inputDataType"
        label="输入文件类型"
        width="140"
        sortable
      />
      <el-table-column
        prop="isActive"
        label="激活状态"
        :formatter="activeFormatter"
        width="120"
        sortable
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        sortable
        width="180"
      />
      <el-table-column
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
        sortable
        width="180"
      />
      <el-table-column label="操作" fixed="right" width="640">
        <template #default="scope">
          <!-- <el-popconfirm
            width="220"
            :title="`确定${scope.row.isActive ? '禁用' : '激活'}服务提供商状态么？`"
            @confirm="confirmStatus(scope.row)"
          >
            <template #reference>
              <el-button
                link
                :type="scope.row.isActive ? 'danger' : 'success'"
                size="small"
              >
                {{ scope.row.isActive ? "禁用" : "激活" }}
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm> -->
          <!-- setEnabled -->
          <el-button
            type="success"
            size="small"
            link
            @click="setEnabled(scope.row.id)"
            >设置开关列可见性
          </el-button>
          <el-button
            type="success"
            size="small"
            link
            @click="setMap(scope.row.id)"
            >设置可见映射列
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            @click="openLimit(scope.row)"
          >
            设置行数限制
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="openConfigDialog(scope.row)"
          >
            更新服务配置
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="copyConfigDialog(scope.row)"
          >
            复制
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            @click="openDialog([scope.row])"
          >
            更新服务价格
          </el-button>
          <el-popconfirm
            width="220"
            title="确定删除服务配置么？"
            @confirm="deleteConfig(scope.row.id)"
          >
            <template #reference>
              <el-button link type="danger" size="small">
                删除服务配置
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <ServiceConfigDialog ref="serviceConfigDialogRef" @refresh="onSearch" />
    <ServiceLineLimitsDialog ref="serviceLineLimitsDialogRef" />
    <MapIdsDialog ref="mapIdsDialogRef" />
    <ColumnVisibilityEnabledDialog ref="columnVisibilityEnabledDialogRef" />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { ref, onMounted, reactive } from "vue";
import { ElMessageBox } from "element-plus";
import {
  getAllServiceProviders,
  resetInitialSynced,
  syncServices,
  updateActiveStatus,
  deleteServiceConfig,
  getColumnVisibility
} from "@/api/adminThirdPartyApi";
import { getAllProviders } from "@/api/adminProvidersApi";
import ServicePriceDialog from "./components/ServicePriceDialog.vue";
import ServiceConfigDialog from "./components/ServiceConfigDialog.vue";
import ServiceLineLimitsDialog from "./components/ServiceLineLimitsDialog.vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import MapIdsDialog from "./components/MapIdsDialog.vue";
import ColumnVisibilityEnabledDialog from "./components/ColumnVisibilityEnabledDialog.vue";

const taskConfigStore = useTaskConfigHook();
const tableData = ref([]);
const servicePriceDialogRef = ref(null);
const formRef = ref(null);
const loading = ref(false);
const form = reactive({
  provider: "",
  isActive: "",
  keyword: ""
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const serviceConfigDialogRef = ref(null);
const openConfigDialog = (row?: any) => {
  serviceConfigDialogRef.value?.open(row);
};
const copyConfigDialog = (row?: any) => {
  const copyRow = { ...row };
  delete copyRow.id;
  serviceConfigDialogRef.value?.open(copyRow);
};
const serviceLineLimitsDialogRef = ref(null);
const openLimit = (row?: any) => {
  serviceLineLimitsDialogRef.value?.open(row);
};
const deleteConfig = async (id: any) => {
  try {
    await deleteServiceConfig(id);
    message("删除成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};

const columnVisibilityEnabledDialogRef = ref();
const setEnabled = async (id: string) => {
  try {
    const { data } = await getColumnVisibility(id);
    const { enabled } = data;
    columnVisibilityEnabledDialogRef.value?.open(id, enabled);
  } catch (error) {
    console.log(error);
  }
};
const mapIdsDialogRef = ref();
const setMap = async (id: string) => {
  try {
    const { data } = await getColumnVisibility(id);
    const { visibleColumnIds } = data;
    mapIdsDialogRef.value.open(id, visibleColumnIds);
  } catch (error) {
    console.log(error);
  }
};

// 获取 API 提供商列表
async function onSearch() {
  try {
    loading.value = true;
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...form
    };
    const { data } = await getAllServiceProviders(params);
    const { records, total, size, current } = data;
    tableData.value = records;
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}
const activeFormatter = (row: { isActive: boolean }) => {
  return row.isActive ? "激活" : "未激活";
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};
const confirmStatus = async (row: {
  standardCode: string;
  apiProvider: string;
  isActive: boolean;
}) => {
  try {
    const { standardCode, apiProvider: provider, isActive } = row;
    const params = {
      standardCode,
      provider,
      active: !isActive
    };
    await updateActiveStatus(params);
    message("修改成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const resetInitialSyncedApi = async () => {
  try {
    const { success, message: remake } = await resetInitialSynced();
    if (success) {
      message("重置成功", { type: "success" });
      onSearch();
    } else {
      message(remake || "重置失败", { type: "error" });
    }
  } catch (error) {
    console.error(error);
  }
};
const selectionList = ref([]);
const handleSelectionChange = (val: any) => {
  selectionList.value = val;
};
const openDialog = (list: any) => {
  servicePriceDialogRef.value?.open(list);
};
const openSyncServices = () => {
  ElMessageBox.prompt("请输入提供商名称", "同步第三方服务配置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(async ({ value }) => {
      if (value) {
        await syncServices({ provider: value });
        onSearch();
      }
    })
    .catch(() => {});
};
const providerOptions = ref([]);
onMounted(() => {
  onSearch();
  getAllProviders().then(res => {
    providerOptions.value = res.data.providers;
  });
});
</script>

<style scoped>
.provider-list-page {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.img-box {
  width: 100%;
  display: flex;
  justify-content: center;
  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
